package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.commons.result.ResponseData;
import com.mall.user.ILoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.MemberConverter;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZhaoJiachen on 2021/5/21
 * <p>
 * Description: 用户登录相关功能的实现
 * 1. 用户登录
 * 2. 验证登录
 * 3. 用户退出
 */

@Slf4j
@Component
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    MemberConverter memberConverter;

    @Override
    public UserLoginResponse userLogin(UserLoginRequest userLoginRequest) {

        UserLoginResponse userLoginResponse = new UserLoginResponse();

        try {
            // 合法性检查
            userLoginRequest.requestCheck();

            // 解析
            String userName = userLoginRequest.getUserName();
            String password = userLoginRequest.getPassword();

            // 验证密码是否正确
            String md5_passwd = DigestUtils.md5DigestAsHex(password.getBytes());
            Example memberExample = new Example(Member.class);
            memberExample.createCriteria().andEqualTo("username", userName)
                    .andEqualTo("password", md5_passwd);
            List<Member> members = memberMapper.selectByExample(memberExample);

            Member member = members.get(0);
            // 是否激活
            if ("N".equals(member.getIsVerified())) {
                throw new Exception("用户未激活，请激活后登录");
            }

            // 登陆成功 封装数据
            userLoginResponse = memberConverter.member2UserLoginRes(member);
            JwtTokenUtils build = JwtTokenUtils.builder().msg(String.valueOf(userLoginResponse.getId())).build();
            String jwtToken = build.creatJwtToken(); // 生成token
            userLoginResponse.setToken(jwtToken);
            System.out.println("uid = " + userLoginResponse.getId() + " --- jwtToken = " + jwtToken);
            userLoginResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        } catch (Exception e) { // 异常 反馈错误
            log.error("LoginServiceImpl.userLogin occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(userLoginResponse, e);
        }

        return userLoginResponse;
    }

    @Override
    public CheckAuthResponse validToken(CheckAuthRequest checkAuthRequest) {

        log.info("service开始的请求数据,begin userLoginServiceImpl.validToken: request"+checkAuthRequest);

        //合法性检查
        checkAuthRequest.requestCheck();
        String token = checkAuthRequest.getToken();

        CheckAuthResponse checkAuthResponse = new CheckAuthResponse();
        checkAuthResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        checkAuthResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        try {
            //将token解密信息返回
            String decodeMsg = JwtTokenUtils.builder().token(checkAuthRequest.getToken()).build().freeJwt();
            System.out.println("--------------------msg"+decodeMsg);

            if(StringUtils.isNotBlank(decodeMsg)){
                log.info("validate success");
                //解码的信息只有userId, userName, file
                Integer uid=Integer.parseInt(decodeMsg);
                Member member = memberMapper.selectByPrimaryKey(uid);
                String username = member.getUsername();
                String file = member.getFile();

                //封装输出的数据 uid username file
                Map<String, Object> map = new HashMap<>();
                map.put("uid",uid);
                map.put("username",username);
                map.put("file",file);
//                String userInfo = JSON.toJSONString(map);
//                ObjectMapper objectMapper = new ObjectMapper();
//                String userInfo = objectMapper.writeValueAsString(map);
//                UserInfoDto userInfoDto = memberConverter.member2UserInfo(member);
//                String userinfo = JSON.toJSONString(userInfoDto);
                checkAuthResponse.setUserinfo(map);
                return checkAuthResponse;
            }
            checkAuthResponse.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
        }catch (Exception e){
            log.error("用户登陆验发生意外"+e);
            ExceptionProcessorUtils.wrapperHandlerException(checkAuthResponse,e);
        }
        return checkAuthResponse;

    }
}
